import {NgModule,Component,Input,Output,EventEmitter,Optional,AfterContentInit} from '@angular/core';
import { FormsModule }    from '@angular/forms';
import {CommonModule} from '@angular/common';
import { InputTextModule } from '../inputtext/inputtext';
import { DropdownModule } from '../dropdown/dropdown';
import { DialogModule } from '../dialog/dialog';
import { ButtonModule } from '../button/button';
import { LabelModule } from '../label/label';
import { CalendarModule } from '../calendar/calendar';
import { SelectButtonModule } from '../selectbutton/selectbutton';
import { PanelModule } from '../panel/panel';

@Component({
    selector: 'p-advance',
    template: `
    <p-panel [toggleable]="true" [collapsed]="true">
    <p-header>
      <span class="border-l-1a8fe8 p-l-8">筛选查询</span>
    </p-header>
    <div class="ui-g">
      <div class="ui-g-12 ui-md-8 ui-lg-9 ui-xl-10">
           <p-selectButton [options]="types" [optionLabel]="selectLabel" (onChange)="search()" [(ngModel)]="selectedType"></p-selectButton>
      </div>
      <div class="ui-g-12 ui-md-4 ui-lg-3 ui-xl-2">
          <div class="relative">
              <input type="text" pInputText class="width-full p-input" [(ngModel)]="searchObj[inputModel]" (keyUp.enter) ="search()" placeholder="名称/编号">    
              <span class="icon-search-right"></span>
           </div>
      </div>
    </div>
    <div class="p-2-8 m-10-0">
      <div class="inline-block" *ngFor="let item of commons">
          <div [ngSwitch]="item.type">
          <span>{{item?.title}}: </span>
                <input *ngSwitchCase="'input'" [placeholder]="item.placeholder" type="text" [name]="item.keyword" class="p-input width-200 m-r-30" pInputText [(ngModel)]="searchObj[item.keyword]">
                <div  *ngSwitchCase="'date'" class="width-200 m-r-30 inline-block">
                    <p-calendar [placeholder]="item.placeholder" [name]="item.keyword" [(ngModel)]="searchObj[item.keyword]" styleClass="p-calendar"  inputStyleClass="height-full"></p-calendar>
                </div>
                <p-dropdown [placeholder]="item.placeholder" *ngSwitchCase="'dropdown'" styleClass="width-200 m-r-30" [dataKey]="item.datakey" [optionLabel]="item.optionLabel" [options]="dataObj[item.keyword] || []"  [(ngModel)]="selectedObj[item.keyword]"></p-dropdown>
          </div>
      </div>
      <div class="inline-block pull-right">
          <button pButton type="button" (click)="search()" label="查询" class="btn btn-success pull-right"></button>
      </div>
    </div>
    <div class="ui-g">
      <div class="ui-g-12 ui-md-8 ui-lg-9 ui-xl-10">
          <span *ngFor="let item of selectedItem;index as i" class="v-middle m-r-20">
              <span [ngSwitch]="item.type">
              <div class="inline-block icon-text" [ngClass]="{'border-1a91eb':!item.focus,'border-fff':item.focus}"  *ngSwitchCase="'input'">
              <input type="text" [ngClass]="{'color-1a91eb':!item.focus}" class="p-input border-none width-110 height-34"  pInputText (focus)="item.focus = true" (keyUp.enter)="$event.target.blur()" 
              (blur)="item.focus = false"  [(ngModel)]="searchObj[item.keyword]">
              <span class="ui-clickable fa fa-close m-t-0 p-label-icon" (click)="onRemove(i)" *ngIf="!item.focus"></span>
          </div>
                      <p-calendar *ngSwitchCase="'date'" [showIcon]="false" [canDelete]="true" (onRemove)="onRemove(i)"  [(ngModel)]="searchObj[item.keyword]" styleClass="p-calendar width-110" inputStyleClass="height-full"></p-calendar>
                      <p-dropdown *ngSwitchCase="'dropdown'" styleClass="width-110" placeholder="请选择"  [canDelete]="true" (onRemove)="onRemove(i)"  [dataKey]="item.datakey" [optionLabel]="item.optionLabel" [options]="dataObj[item.keyword] || []"  [(ngModel)]="selectedObj[item.keyword]"></p-dropdown>
              </span>
          </span>
      </div>    
      <div class="ui-g-12 ui-md-4 ui-lg-3 ui-xl-2">
            <button icon="fa-search-plus" pButton type="button" (click)="advanceStart()" label="高级搜索" class="btn btn-primary pull-right"></button>
      </div>
    </div> 
  </p-panel>
  <p-dialog header="添加筛选条件" [(visible)]="display" modal="modal" width="800" [responsive]="true">
  <p-header>
      <span class="font-12">  {{ remark || '(注：将您要添加的筛选条件进行改动，就视为添加该筛选条件。如不需要，请改回默认。)'}}</span>
  </p-header>

  <div class="ui-g">
      <div class="ui-g-4" *ngFor="let item of choices">
          <div class="ui-g-3 p-0 text-right"><span class="line-height-36">{{item.title}}: </span></div>
          <div class="ui-g-9 p-0"  [ngSwitch]="item.type">
                    <p-calendar *ngSwitchCase="'date'" [(ngModel)]="dialogSearch[item.keyword]" styleClass="p-calendar" inputStyleClass="height-full"></p-calendar>
                  <input *ngSwitchCase="'input'" type="text" [name]="item.keyword" class="p-input" pInputText [(ngModel)]="dialogSearch[item.keyword]">
                  <p-dropdown *ngSwitchCase="'dropdown'" [dataKey]="item.datakey" placeholder="请选择" styleClass="width-full" [optionLabel]="item.optionLabel" [options]="dataObj[item.keyword] || []"  [(ngModel)]="dialogSelect[item.keyword]"></p-dropdown>
          </div>
            
      </div>
  </div>    
  <p-footer>
          <p-label *ngFor="let label of savedLabel;index as i" styleClass="m-l-10 m-t-4 pull-left" (onSelect)="onSelect(i)" (onClose)="close(i)" [label]="label.name" [active]="label.current" ></p-label>
          <button pButton type="button" (click)="reset()" label="重置" class="btn btn-secondary" ></button>
          <button pButton type="button" (click)="advanceSearch()" label="查询" class="btn btn-success"></button>
          <button pButton type="button" (click)="displayLabel = true" label="保存条件" class="btn btn-primary"></button>
  </p-footer>
</p-dialog>
  <p-dialog header="请输入标签名称" [(visible)]="displayLabel" modal="modal" width="400" [responsive]="true">
  <div class="ui-g">
    <input id="input" style="width: auto !important;margin: 35px auto;" (keyup)="isExist(name)" type="text" maxlength="5" required class="p-input" size="30" pInputText [(ngModel)]="name">
  </div>    
  <div class="ui-g text-center">
    <div class="ui-g-12">
    <button pButton type="button" (click)="displayLabel = false" label="取消" class="btn btn-secondary m-15" ></button>
    <button pButton type="button" (click)="save(name)" label="确定" [disabled]="!canSave || !name" class="btn btn-primary m-15"></button>
    </div>
  </div>    

</p-dialog>
    `
  

})
export class UIAdvance implements AfterContentInit{

    @Output() advanceClick: EventEmitter<any> = new EventEmitter();
    
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    @Output() onSearch: EventEmitter<any> = new EventEmitter();

    @Output() onSavelabel: EventEmitter<any> = new EventEmitter();

    @Input() remark:string;

    @Input() selectItem: any[] = [];

    @Input() selectLabel:string = 'name';

    @Input() selectKey:string = 'keyword';

    @Input() inputModel:string = 'search';

    @Input() commonOptions:any[] = [];

    @Input() selectedItem: any[] = [];

    @Input() datas:any = {};

    @Input() choices:any = {};
    
    @Input() labels:any = [];

    name:string;

    canSave:boolean = true;

    display:boolean;

    dialogSearch:any = {};

    dialogSelect:any = {};

    selectedType:any = {};

    searchObj:any = {};

    selectedObj:any = {};

    displayLabel:boolean;

    ngAfterContentInit() {
        let index = this.savedLabel.findIndex(val=>val.current);
        if(index<0){return}
        this.getSelectLabel(index);
    }

    get dataObj():any{
        return this.datas
    };

    get savedLabel(){
        return this.labels
    }

    get types(){
        return this.selectItem 
    }

    get commons(){
        return this.commonOptions 
    }

    isExist(name){
        let index = this.savedLabel.findIndex(val=>val.name == name);
        this.canSave = index<0 && !!this.getSavedata().length;
    }

    advanceStart(){
        this.advanceClick.emit();
        this.display = true;
    }

    onSelect(event){
        this.dialogSearch = {};
        this.dialogSelect = {}
        this.savedLabel.map((val,index)=>{
            val.current = index == event?true:false;
        });
        this.getSelectLabel(event);
    }

    getSelectLabel(event){

        let select = this.savedLabel[event];
        if(!select.data){return}
        select.data.map(val=>{
            if(val.type == 'input'){
                this.dialogSearch[val.keyword] = val.data
            }
            if(val.type == 'dropdown'){
                this.dialogSelect[val.keyword] = val.data;
            }
        })
    }

    advanceSearch(){
        this.selectedItem = this.choices.filter(val=> {
            let select = this.dialogSelect[val.keyword];
            let search = this.dialogSearch[val.keyword];
            this.searchObj[val.keyword] = search || (select?select[val.datakey]:undefined)
            this.selectedObj[val.keyword] = select
            return select || search;
        } );
        this.display = false;
        this.search();
    }

    onRemove(i){
        this.selectedItem = this.selectedItem.filter((val,index)=>{
           if(index==i){
               this.searchObj[val.keyword] = undefined;
               this.selectedObj[val.keyword] = undefined;
            } 
           return index != i
        });
        this.search();
    }

    close(i){
        this.labels = this.labels.filter((val,index)=>i!=index);
        this.onClose.emit(i);
    }

    save(name){
        let data = this.getSavedata();
        this.onSavelabel.emit({name:name,data:data});
        console.log({name:name,data:data})
    }

    getSavedata(){
        let data = [];
        this.choices.map(val=>{
            let item = {};
            let select = this.dialogSelect[val.keyword];
            let search = this.dialogSearch[val.keyword];
            if(select || search){
                item['keyword'] = val.keyword;
                item['type'] = val.type;
                item['data'] = select || search;
                data.push(item)
            }
        })
        return data;
    }

    search(){
        this.searchObj[this.selectKey] = this.selectedType[this.selectKey]; 
        this.onSearch.emit(this.searchObj)
    }

    reset(){}
        
}



@NgModule({
    imports: [FormsModule,CommonModule,PanelModule,InputTextModule,DropdownModule,DialogModule,ButtonModule,LabelModule,CalendarModule,SelectButtonModule],
    exports: [UIAdvance],
    declarations: [UIAdvance]
})
export class AdvanceModule { }